package com.rainkaze.IntelliDrawNote.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rainkaze.IntelliDrawNote.R;
import com.rainkaze.IntelliDrawNote.adapter.AIChatAdapter;
import com.rainkaze.IntelliDrawNote.bean.ChatMessage;
import com.rainkaze.IntelliDrawNote.utils.AiHelperUtils;
import com.rainkaze.IntelliDrawNote.db.MyDbHelper;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class AiFragment extends Fragment {

    private RecyclerView chatRecyclerView;
    private EditText messageEditText;
    private Button sendButton;

    private AIChatAdapter chatAdapter;
    private List<ChatMessage> chatMessages;

    private boolean isWaitingResponse = false; // 标记是否等待AI回复
    private Handler timeoutHandler = new Handler(); // 超时处理器
    private Runnable timeoutRunnable; // 用于延迟任务

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_ai, container, false);

        chatRecyclerView = rootView.findViewById(R.id.chatRecyclerView);
        messageEditText = rootView.findViewById(R.id.messageEditText);
        sendButton = rootView.findViewById(R.id.sendButton);

        // 初始化聊天记录并加载历史记录
        chatMessages = new ArrayList<>();
        MyDbHelper dbHelper = new MyDbHelper(getContext());
        List<ChatMessage> historyMessages = dbHelper.getChatHistory();
        if(historyMessages != null && !historyMessages.isEmpty()){
            chatMessages.addAll(historyMessages);
        }
        chatAdapter = new AIChatAdapter(chatMessages);
        chatRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        chatRecyclerView.setAdapter(chatAdapter);

        // 发送按钮点击事件
        sendButton.setOnClickListener(v -> {
            if (isWaitingResponse) {
                Toast.makeText(getContext(), "请等待AI回复...", Toast.LENGTH_SHORT).show();
                return;
            }

            String userMessage = messageEditText.getText().toString().trim();
            if (!TextUtils.isEmpty(userMessage)) {
                // 添加用户消息
                ChatMessage userChatMessage = new ChatMessage(userMessage, true);
                chatMessages.add(userChatMessage);
                chatAdapter.notifyItemInserted(chatMessages.size() - 1);
                chatRecyclerView.smoothScrollToPosition(chatMessages.size() - 1);
                dbHelper.insertChatMessage(userChatMessage);

                messageEditText.setText("");
                isWaitingResponse = true;
                sendButton.setEnabled(false); // 禁用按钮

                // 设置超时回调（10秒后提示超时，但并没有终止线程）
                //TODO: 有时会阻塞主线程，导致界面卡死。
                timeoutRunnable = () -> {
                    if (isWaitingResponse) {
                        isWaitingResponse = false;
                        sendButton.setEnabled(true);
                        Toast.makeText(getContext(), "AI 响应超时，请重试", Toast.LENGTH_SHORT).show();
                    }
                };
                timeoutHandler.postDelayed(timeoutRunnable, 10000); // 10秒

                // 请求AI回复
                AiHelperUtils.sendRequest(userMessage, new AiHelperUtils.AiCallback() {
                    @Override
                    public void onSuccess(String response) {
                        timeoutHandler.removeCallbacks(timeoutRunnable); // 取消超时回调

                        String aiMessage = parseAiResponse(response);
                        ChatMessage aiChatMessage = new ChatMessage(aiMessage, false);
                        chatMessages.add(aiChatMessage);
                        chatAdapter.notifyItemInserted(chatMessages.size() - 1);
                        chatRecyclerView.smoothScrollToPosition(chatMessages.size() - 1);
                        dbHelper.insertChatMessage(aiChatMessage);

                        isWaitingResponse = false;
                        sendButton.setEnabled(true); // 恢复按钮
                    }
                    @Override
                    public void onError(String error) {
                        timeoutHandler.removeCallbacks(timeoutRunnable); // 取消超时回调

                        Toast.makeText(getContext(), "请求失败：" + error, Toast.LENGTH_SHORT).show();
                        isWaitingResponse = false;
                        sendButton.setEnabled(true); // 恢复按钮
                    }
                });
            }
        });

        return rootView;
    }
    // 解析AI回复的内容（从JSON中提取AI的回应）
    private String parseAiResponse(String response) {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            JSONArray choices = jsonResponse.getJSONArray("choices");
            JSONObject firstChoice = choices.getJSONObject(0);
            JSONObject message = firstChoice.getJSONObject("message");
            return message.getString("content");
        } catch (Exception e) {
            e.printStackTrace();
            return "解析 AI 回复失败";
        }
    }
    @Override
    public void onPause() {
        super.onPause();
        // 切换页面时取消正在等待的请求
        timeoutHandler.removeCallbacks(timeoutRunnable);
        isWaitingResponse = false;
    }
    @Override
    public void onResume() {
        super.onResume();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        timeoutHandler.removeCallbacksAndMessages(null); // 清除所有定时器
        isWaitingResponse = false;
    }
}
